<!-- 多图片上传 -->
<template>
    <el-upload v-model:file-list="state.fileList" :action="data.actionUrl" :headers="data.headers"
        list-type="picture-card" :on-success="handleAvatarSuccess" :on-preview="handlePictureCardPreview"
        :limit="data.limit" :on-remove="handleRemove" :before-upload="beforeAvatarUpload">
        <el-icon>
            <Plus />
        </el-icon>
        <template #tip>
            <div class="el-upload__tip">
                {{ data.tip }}
            </div>
        </template>
        <template #file="{ file }">
            <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                    <span v-if="data.sort" class="el-upload-list__item-delete" @click="sort(0, file)">
                        <el-icon>
                            <ArrowLeft />
                        </el-icon>
                    </span>
                    <span class="el-upload-list__item-delete" @click="handlePictureCardPreview(file)">
                        <el-icon>
                            <Search />
                        </el-icon>
                    </span>
                    <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                        <el-icon>
                            <Delete />
                        </el-icon>
                    </span>
                    <span v-if="data.sort" class="el-upload-list__item-delete" @click="sort(1, file)">
                        <el-icon>
                            <ArrowRight />
                        </el-icon>
                    </span>
                </span>
            </div>
        </template>
    </el-upload>
    <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
const emit = defineEmits(['uploadImageClick'])
import type { UploadProps, UploadUserFile } from 'element-plus'
const props = defineProps({
    data: {
        type: Object,
        default: () => { }
    }
})
const state = reactive({
    fileList: [] as any
})
function fileUrl(data) {
    data.forEach(element => {
        state.fileList.push(element)
    });
}

function fileUrls(data) {
    let array = ""
    for (let index = 0; index < data.length; index++) {
        if (index == 0) {
            array = data[index].response.data.ossId
        } else {
            array = array + "," + data[index].response.data.ossId
        }
    }
    return array
}
fileUrl(props.data.urls)
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const sort = (index, uploadFile: any) => {
    let indexs = state.fileList.findIndex(obj => obj.response.data.ossId === uploadFile.response.data.ossId);
    if (index == 0 && indexs > 0) {//向前排序
        [state.fileList[indexs], state.fileList[indexs - 1]] = [state.fileList[indexs - 1], state.fileList[indexs]];
        emit('uploadImageClick', fileUrls(state.fileList))
    }
    if (index == 1 && indexs < state.fileList.length - 1) {
        // console.log("后移",indexs);
        [state.fileList[indexs], state.fileList[indexs + 1]] = [state.fileList[indexs + 1], state.fileList[indexs]];
        emit('uploadImageClick', fileUrls(state.fileList))
    }

}
const handleRemove: UploadProps['onRemove'] = (uploadFile: any) => {
    console.log("多图片删除成功", state.fileList, uploadFile)
    state.fileList = state.fileList.filter(obj => obj.response.data.ossId !== uploadFile.response.data.ossId);
    emit('uploadImageClick', fileUrls(state.fileList))
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log("多图片上传成功：", response, uploadFile);
    emit('uploadImageClick', fileUrls(state.fileList))
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    console.log("图片：", props.data.whSize);
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/jpg' && rawFile.type !== 'image/png') {
        ElMessage.error('图片格式有误! 仅支持jpg、jpeg、png格式!')
        return false;
    } else if (rawFile.size / 1024 / 1024 > (props.data.size ? props.data.size : 2)) {
        ElMessage.error(`图片大小不超过${props.data.size ? props.data.size : 2}MB!`)
        return false;
    }
    if (props.data.whSize) {
        let widthSize=props.data.widthSize,heightSize=props.data.heightSize
        let imageBool=true
        return new Promise((resolve, reject) => {
            var reader = new FileReader();
            reader.onload = function (event: any) {
                var txt: any = event.target.result;
                var img: any = document.createElement("img");
                img.src = txt;
                img.onload = function () {
                    console.log(img.width, img.height);
                    if (img.width != widthSize || img.height !=heightSize) {
                        reject(ElMessage.error('请上传正确尺寸的图片！'));
                        
                    }else{
                        resolve()
                    }
                }
            };
            reader.readAsDataURL(rawFile);
        })
    }
    return true
}
</script>